import { http, downloadBlob } from '@/utils/http'
import type { AxiosResponseHeaders } from 'axios'

type TableID = number | string | string[]

// 查询生成表数据
export function listTable(params?: object) {
  return http.request<HttpPaginationResponse<Array<any>>>('get', '/code/gen/list', {
    params,
  })
}
// 查询db数据库列表
export function listDbTable(params?: object) {
  return http.request<HttpPaginationResponse<Array<any>>>('get', '/code/gen/db/list', {
    params,
  })
}

// 查询表详细信息
export function getGenTable(tableId: TableID) {
  return http.request<HttpResponse<{ [key: string]: any }>>('get', '/code/gen/' + tableId)
}

// 修改代码生成信息
export function updateGenTable(data?: object) {
  return http.request<HttpResponse<Object>>('put', '/code/gen/', { data })
}

// 导入表
export function importTable(data?: object) {
  return http.request<HttpResponse<Object>>('post', '/code/gen/importTable', {
    data,
  })
}

// 预览生成代码
export function previewTable(tableId: TableID) {
  return http.request<HttpResponse<Object>>('get', '/code/gen/preview/' + tableId)
}

// 删除表数据
export function delTable(tableId: TableID) {
  return http.request<HttpResponse<Object>>('delete', '/code/gen/' + tableId)
}

// 生成代码（自定义路径）
export function genCode(tableName: string) {
  return http.request<HttpResponse<Object>>('get', '/code/gen/genCode/' + tableName)
}

// 同步数据库
export function synchDb(tableName: string) {
  return http.request<HttpResponse<Object>>('get', '/code/gen/synchDb/' + tableName)
}

// 生成代码
export async function downLoadCode(tbNames, filename) {
  return http
    .get<{}, { data: Blob; headers: AxiosResponseHeaders }>(
      '/code/gen/batchGenCode?tables=' + tbNames,
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        responseType: 'blob',
      }
    )
    .then((data) => {
      const blob = new Blob([data.data])
      downloadBlob(blob, filename)
    })
}
